from django.forms.models import model_to_dict


# 模型转字典
def utils_model_to_dict(model, *args, **kwargs):
    data = model_to_dict(model)
    data["oid"] = model.oid
    data["product"] = {
        "pid": model.product.pid,
        "name": model.product.name,
        "points": model.product.points,
        "stock": model.product.stock,
        "sold": model.product.sold,
    }
    
    # 处理日期时间字段，转换为字符串格式
    if hasattr(model, 'create_time'):
        data['create_time'] = model.create_time.strftime('%Y-%m-%d %H:%M:%S')
    if hasattr(model, 'update_time'):
        data['update_time'] = model.update_time.strftime('%Y-%m-%d %H:%M:%S')
    # 处理外键字段
    if hasattr(model, 'user') and model.user:
        data['user_id'] = model.user.uid
        data['username'] = model.user.username
    if hasattr(model, 'product') and model.product:
        data['product_id'] = model.product.pid
        data['product_name'] = model.product.name
    return data